package com.ruoyi.readcard.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.AsyncRestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.Map;

/**
 * @ClassName RestUtils
 * @Description TODO
 * @Author 17179
 * @Date 2023/11/7 14:14
 **/
@Configuration
@Slf4j
public class RestUtils {

    /**
     * 运营平台接口基础地址
     */
    private static String baseUrl;


    @Value("${livenServer.url}")
    public  void setToUrl(String url) {
        this.baseUrl = url;
    }


    private static final AsyncRestTemplate restTemplate = new  AsyncRestTemplate();



    public static JSONObject post(String url, Map<String,String> urlParams, JSONObject json){
        //组装url
        url = baseUrl+url;
        return post(urlToUri(url,urlParams),json);
    }

    public static JSONObject post(String url, Object json){
        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(json);
        //组装urL
        url = baseUrl+url;
        return post(URI.create(url),jsonObject);
    }

    /**
     * 请求到server运营平台 post异步请求
     * @param url
     * @param json
     */
    public static void postAsync(String url, Object json){
        try{
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(json);
            //组装urL
            url = baseUrl+url;
            log.info("充电桩-->平台请求: url={}, json={}", url, json);
            postAsync(URI.create(url),jsonObject);
        }catch (Exception e){
            e.printStackTrace();
            log.error("http请求平台后端失败,{}", e.getMessage());
        }
    }
    /**
     * 请求到server运营平台 post异步请求
     * @param json
     */
    public static void postAsync(Object json){
        try{
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(json);
            postAsync(URI.create(baseUrl),jsonObject);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 请求到admin-server运营平台 post异步请求
     * @param url
     * @param json
     */
    public static void postAsyncAdminServer(String url, Object json){
        try{
            JSONObject jsonObject = (JSONObject) JSONObject.toJSON(json);
            //组装urL
            url = url;
            postAsync(URI.create(url),jsonObject);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("http请求后台管理后端失败！！！");
        }
    }
    private static JSONObject post(URI uri, JSONObject json){
        //组装url
        //设置提交json格式数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> request = new HttpEntity(json, headers);
        ResponseEntity<JSONObject> responseEntity = null;
        try{
             restTemplate.postForEntity(uri,request, JSONObject.class);
            serverIsRight(responseEntity);  //判断服务器返回状态码
        }catch (Exception i){
            i.printStackTrace();
        }

        return responseEntity.getBody();
    }

    private static void postAsync(URI uri, JSONObject json){
        //组装url
        //设置提交json格式数据
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<JSONObject> request = new HttpEntity(json, headers);
        try{
            restTemplate.postForEntity(uri,request, JSONObject.class);
        }catch (Exception e){
            e.printStackTrace();
            log.error("{}",e);
        }
    }

    private static URI urlToUri(String url,Map<String,String> urlParams){
        //设置提交json格式数据
        UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
        for(Map.Entry<String,String> entry : urlParams.entrySet())  {
            uriBuilder.queryParam((String)entry.getKey(),  (String) entry.getValue()) ;
        }
        return  uriBuilder.build(true).toUri();
    }

    public static JSONObject upload(String url, MultiValueMap formParams){
        //设置表单提交
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(formParams, headers);
        ResponseEntity<JSONObject> responseEntity = null;
                restTemplate.postForEntity(url,request, JSONObject.class);
        serverIsRight(responseEntity);  //判断服务器返回状态码
        return responseEntity.getBody();
    }

//    public static String download(String url,String targetPath) throws IOException {
//
//        ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url, byte[].class);
//        if(rsp.getStatusCode() != HttpStatus.OK){
//            System.out.println("文件下载请求结果状态码：" + rsp.getStatusCode());
//        }
//        // 将下载下来的文件内容保存到本地
//        Files.write(Paths.get(targetPath), Objects.requireNonNull(rsp.getBody()));
//        return targetPath;
//
//    }

//    public static byte[] download(String url){
//        ResponseEntity<byte[]> rsp = restTemplate.getForEntity(url, byte[].class);
//        return rsp.getBody();
//    }

    private static void serverIsRight(ResponseEntity responseEntity){
        if(responseEntity.getStatusCodeValue()==200){
        }else {
            System.out.println("服务器请求异常：{}"+responseEntity.getStatusCodeValue());
        }
    }

}
